import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    username: '',
    password: '',
    confirmPassword: '',
    nickname: ''
  },

  onUsernameChange(e) {
    this.setData({
      username: e.detail.value
    });
  },

  onPasswordChange(e) {
    this.setData({
      password: e.detail.value
    });
  },

  onConfirmPasswordChange(e) {
    this.setData({
      confirmPassword: e.detail.value
    });
  },

  onNicknameChange(e) {
    this.setData({
      nickname: e.detail.value
    });
  },

  onRegister() {
    const { username, password, confirmPassword, nickname } = this.data;
    
    if (!username.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入用户名',
        theme: 'warning'
      });
      return;
    }
    
    if (!password.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入密码',
        theme: 'warning'
      });
      return;
    }
    
    if (password !== confirmPassword) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '两次密码输入不一致',
        theme: 'warning'
      });
      return;
    }
    
    if (!nickname.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入昵称',
        theme: 'warning'
      });
      return;
    }

    // 调用注册接口
    wx.request({
      url: 'http://localhost:8080/api/wx/register',
      method: 'POST',
      data: {
        username: username.trim(),
        password: password.trim(),
        nickname: nickname.trim()
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.statusCode === 200) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '注册成功，请登录',
            theme: 'success'
          });
          
          setTimeout(() => {
            wx.navigateBack();
          }, 800);
        } else {
          Toast({
            context: this,
            selector: '#t-toast',
            message: res.data.message || '注册失败',
            theme: 'error'
          });
        }
      },
      fail: (err) => {
        Toast({
          context: this,
          selector: '#t-toast',
          message: '网络请求失败',
          theme: 'error'
        });
        console.error('注册请求失败:', err);
      }
    });
  },

  goToLogin() {
    wx.navigateBack();
  }
});
